# ActsAsRatable
#

module Yng 
  module Acts #:nodoc:
    module Ratable #:nodoc:

      def self.included(mod)
          mod.extend(ClassMethods)
      end
      
      module ClassMethods
        def acts_as_ratable 
          has_one :rate, :as => :ratable
          before_create :create_rate

          include Yng::Acts::Ratable::InstanceMethods
          extend Yng::Acts::Ratable::SingletonMethods

        end
      end

      module InstanceMethods
        def average_score
          rate.average_score
        end
        
        def votes
          rate.votes        
        end

        def rate_it!(user,score)
          begin
            rating=Rating.new
            rating.user_id=user.id
            rating.score=score
            rate.ratings << rating
            rate.save!  # This might throw an exception if the user already rated it.
            ActiveRecord::Base.connection.update(
                "update rates set total_score=total_score+#{score},votes=votes+1 where id=#{rate.id}")
          rescue ActiveRecord::RecordNotSaved
            false
          rescue => e
            logger.error e
            false
          else
            true
          end
        end

        def rated?(user)
          Rating.find(:first, 
                      :conditions => 
                      ["rate_id = ? and user_id = ? ",rate.id,user.id ]).nil? ? false : true
        end
        
        private
        
        def create_rate
            rate=Rate.new
        end
      end

      module SingletonMethods
      end

    end

  end

end
